<?php

namespace app\db\model;

use think\Db;
use think\Model;

class DbUser extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $dbName     = 'db_user';

    # --------------------------------- 查询类接口 START------------------------------------
    /**
     * 获取用户信息
     * @param int  $user_id 用户id
     * @author MSQ 2021-8-2
    **/
    public function getDetails($user_id = 0,$field = '*')
    {
        $where = [
            'status'          => 1,
            'relation_status' => 1,
        ];
        if (is_array($user_id)) {
            $where['id'] = ['IN',$user_id];

            if ($field && $field != '*' && count(explode(',', $field)) == 1) {
                // 只取一个字段
                $info = $this->where($where)->column($field);
            }else{
                $info = db($this->dbName)->field($field)->where($where)->select();
            }
        }else{
            $where['id'] = $user_id;

            if ($field && $field != '*' && count(explode(',', $field)) == 1) {
                // 只取一个字段
                $info = $this->where($where)->value($field);
            }else{
                $info = db($this->dbName)->field($field)->where($where)->find();
            }
        }
        
        
        return $info;
    }
    /**
     * 根据身份证/住院号获取用户ID
     * @param int  $database_id 数据库ID
     *             $id_card_no 身份证号
     *             $hospital_number 住院号
     * @author MSQ 2021-8-5
    **/
    public function getUserIdByIDCardOrHospitalNumber($database_id = 0,$id_card_no = '',$hospital_number = '')
    {
        $user_id = 0;

        if (!$database_id) return false;
        if (!$id_card_no && !$hospital_number) return $user_id;

        $where = ['status' => 1,'database_id' => $database_id];
        # 优先找身份证号
        if ($id_card_no) {
            $where['id_card_number'] = $id_card_no;
            $user_id = $this->where($where)->value('id');
            if ($user_id) return $user_id;
            unset($where['id_card_number']);
        }
        # 再找住院号
        if ($hospital_number) {
            $hospitalUserKey = $this->getHospitalUserKey();
            $where[$hospitalUserKey] = $hospital_number;
            $user_id = $this->where($where)->value('id');
            if ($user_id) return $user_id;
        }
        return $user_id;
    }
    /**
     * 生成QID
     * @author MSQ 2021-8-5
    **/
    public function getUserNumber()
    {
        # 目前最大QID
        $n = $this->order('user_number DESC')->value('user_number');

        //处理--取日期
        $d = substr($n, 1,6);

        //处理--号数
        $i = substr($n, 7);

        $date = date('ymd');

        $data = [];

        if ($date == $d) {
            $Qid = 'Q'.$date.sprintf("%05d", (((int)$i)+1));

        }else{
            $Qid = 'Q'.$date.sprintf("%05d", 1);
        }
        return $Qid;
    }
    /**
     * 获取数据库用户列表
     * @author MSQ 2021-8-5
    **/
    public function getDatabaseUserList($param = [])
    {
        $databaseInfo = $param['database_info'];
        $database_id  = $databaseInfo['id'];
        $data = ['list' => [],'total' => 0];
        $whereStatus = 1;
        $where = [
            'u.status' => $whereStatus,
            'u.relation_status' => $whereStatus,
        ];
        if ($param['search']) $where['u.user_number|u.hospital_number|u.user_name|u.id_card_number'] = ['LIKE', '%'.$param['search'].'%'];
        
        $pageStart = ($param['page']['idx']-1)*$param['page']['sum'];
        $limit = $pageStart.','.$param['page']['sum'];
        $field = '
            u.id,u.user_number,u.hospital_number,
            u.user_name,u.id_card_number,u.user_sex,
            u.user_age,u.create_time,u.create_type';

        if ($databaseInfo['parent_id']) {
            # 子库 获取复制的病例
            $where['u.database_id']  = $databaseInfo['parent_id'];// 创建的数据库 统一总库
            // $where['c.origin_db_id'] = $databaseInfo['parent_id'];// 复制表 来源数据库-总库
            $where['c.goal_db_id']   = $database_id;// 复制表 目标数据库-子库
            $where['c.status']       = $whereStatus;// 复制表 状态正常

            $list = db('db_user_relation_db_child')
                ->alias('c')->field($field)
                ->where($where)->join('db_user u','u.id=c.user_id')
                ->order('u.create_time '.$param['order_sort'])
                ->limit($limit)->select();
            $total = db('db_user_relation_db_child')->alias('c')
                ->where($where)->join('db_user u','u.id=c.user_id')
                ->count();
            $parDatabaseName = model('DbDatabase')->getDetails($databaseInfo['parent_id'],'database_name');
        }else{
            # 总库
            $where['u.database_id'] = $database_id;
            $list = db($this->dbName)->field($field)->alias('u')
                ->where($where)->order('u.create_time '.$param['order_sort'])
                ->limit($limit)->select();
            $total = db($this->dbName)->alias('u')->where($where)->count();
        }

        foreach ($list as $key => $user) {
            $user_from_text = '';
            if (!$user['create_type']) {
                $user_from_text = '录入用户';
            }elseif ($user['create_type'] == 1) {
                $user_from_text = '导入用户';
            }

            # 来源
            $user['user_from_text'] = $user_from_text;
            if ($databaseInfo['parent_id']) {
                # 子库-加上团队
                if (!$user['create_type']) {
                    $user['user_from_text'] = '团队：'.$parDatabaseName.$user_from_text;
                }elseif ($user['create_type'] == 1) {
                    $user['user_from_text'] = '团队：'.$parDatabaseName.$user_from_text;
                }
            }
            $user['create_date'] = date('Y-m-d',$user['create_time']);
            $user['id_card_status'] = true;// 返回固定值 便于前端点击身份证隐藏/显示
            $list[$key] = $user;
        }
        $data['list']   = $list;
        $data['total']  = $total;
        return $data;
    }
    /**
     * 获取总库库用户列表
     * @author MSQ 2021-8-7
    **/
    public function getParDbAllUserList($database_id  = 0,$search = '',$field = '*')
    {
        $where = [
            'status'          => 1,
            'relation_status' => 1,
            'database_id'     => $database_id
        ];
        if ($search) $where['user_number|hospital_number|user_name|id_card_number'] = ['LIKE', '%'.$search.'%'];
        
        if ($field && $field != '*' && count(explode(',', $field)) == 1) {
            // 只取一个字段
            $list = db($this->dbName)->where($where)->column($field);   
        }else{
            $list = db($this->dbName)->field($field)->where($where)->select();   

        }

        if (!$list) return [];
        return $list;
    }
    /**
     * 获取用户表住院号字段
     * @author MSQ 2021-8-19
    **/
    public function getHospitalUserKey()
    {
        $key = 'hospital_number';
        return $key;
    }

    /**
     * @Notes:getUserAllCount
     * @param string $database_id      数据库ID
     * @param int $parent_id           总库ID
     * @return int|string
     * @author:WuXiaoMing
     * Date:2021/8/24
     * Time:4:03 下午
     */
    public function getUserAllCount($database_id='',$parent_id=0)
    {
        if($parent_id){ //子库用户
            $where =[
                // 'origin_db_id'=>$parent_id, // 复制表 来源数据库-总库
                'goal_db_id'=>$database_id,  // 复制表 目标数据库-子库
                'status'=>1,// 复制表 状态正常
            ];
            $total = db('db_user_relation_db_child')->where($where)->count();
        }else{
            $where = [
                'status'          => 1,
                'relation_status' => 1,
                'database_id'     => $database_id
            ];
            $total = db($this->dbName)->where($where)->count();
        }
        return $total;
    }
    /**
     * 获取数据库用户列表
     * 该方法与getDatabaseUserList类似 区别在于不分页
     * @author MSQ 2021-8-5
    **/
    public function getAllDbUserList($database_id = 0,$parent_id = 0,$search = '',$field = 'u.*')
    {
        $whereStatus = 1;
        $where = [
            'u.status' => $whereStatus,
            'u.relation_status' => $whereStatus,
        ];
        if ($search) $where['u.user_number|u.hospital_number|u.user_name|u.id_card_number'] = ['LIKE', '%'.$search.'%'];

        if ($parent_id) {
            # 子库 获取复制的病例
            $where['u.database_id']  = $parent_id;// 创建的数据库 统一总库
            // $where['c.origin_db_id'] = $parent_id;// 复制表 来源数据库-总库
            $where['c.goal_db_id']   = $database_id;// 复制表 目标数据库-子库
            $where['c.status']       = $whereStatus;// 复制表 状态正常

            $list = db('db_user_relation_db_child')
                ->alias('c')->field($field)
                ->join('db_user u','u.id=c.user_id')
                ->where($where)
                ->order('u.create_time DESC')
                ->select();
        }else{
            # 总库
            $where['u.database_id'] = $database_id;
            $list = db($this->dbName)->alias('u')
                ->field($field)->where($where)
                ->order('u.create_time DESC')->select();
        }
        return $list;
    }
    # ---------------------------------- 查询类接口 END-------------------------------------


    # ------------------------------- 数据处理类接口 START ----------------------------------
    /**
     * 创建用户
     * @param int  $database_id 数据库ID
     *             $id_card_no 身份证号
     *             $hospital_number 住院号
     * @author MSQ 2021-8-5
    **/
    public function createCaseUser($data = [])
    {
        $database_id  = $data['database_id'];
        $master_db_id = $data['master_db_id'];// 总库ID

        $user_number = $this->getUserNumber();
        # 添加用户数据
        $addData = [
            'database_id'     => $master_db_id, // 数据库id
            'user_number'     => $user_number,
            'id_card_number'  => $data['id_card_number'],// 身份证号
            'hospital_number' => $data['hospital_number'],// 住院号
            'user_name'       => $data['user_name'],// 姓名
            'usercare_id'     => $data['usercare_id'],// 创建者医务id
            'user_birthday'   => $data['user_birthday'],// 出生日期
            'user_sex'        => $data['user_sex'],// 性别
            'user_age'        => $data['user_age'],// 年龄
        ];

        $this->setAttr('id',null)->isUpdate(false)->save($addData);
        if (!isset($this->id)) return false;
        $user_id = $data['user_id'] = $this->id;      
        if (!$user_id) return false;

        $data['user_number'] = $user_number;
        # 同步添加基础模块关联及回答
        $addDataRes = model('DbData')->createUserSyncBasicItemData($data);

        # 子库新增 同步到子库
        if ($master_db_id != $database_id) {
            $copy_users[] = [
                'user_id'     => $user_id,
                'user_number' => $user_number
            ];
            $copyRes = model('DbUserRelationDbChild')->copyUserToChildDb($master_db_id,[$database_id],$copy_users,$data['usercare_id']);
            if (!$copyRes) return false;
        }
        return true;
    }
    /**
     * 删除用户逻辑
     * @param int  $database_id 数据库ID
     *             $delUserIds 删除的用户id
     * @author MSQ 2021-8-7
    **/
    public function deleteUserLogic($databaseInfo = 0,$delUserIds = [])
    {
        if (!$databaseInfo) return false;

        if (!is_array($databaseInfo)) $databaseInfo = model('DbDatabase')->getDetails($databaseInfo);
        if (!$databaseInfo) return false;
        
        $database_id = $databaseInfo['id'];

        $databasePid = $databaseInfo['parent_id'];

        # 未指定delUserIds 则删除数据库里所有用户
        if (!$delUserIds) {
            $parDbId = $databasePid ? $databasePid : $database_id;
            $allUserIds = $this->getParDbAllUserList($parDbId,'','id');
            if (!$allUserIds) return true;
        }

        if ($databasePid) {
            # 子库删除-删除copy表相关记录
            $saveChildDbUser = model('DbUserRelationDbChild')->deleteChildDbUser(0,$database_id,$delUserIds);
            if ($saveChildDbUser === false) return false;
            return true;
        }else{
            # 总库删除-删除copy表相关记录
            $saveChildDbUser = model('DbUserRelationDbChild')->deleteChildDbUser($database_id,0,$delUserIds);
            if ($saveChildDbUser === false) return false;
        }
            
        $where = ['database_id' => $database_id];
        if ($delUserIds) $where['id'] = ['IN',$delUserIds];
        # 修改user表为删除
        $saveUser = $this->deleteUser($where);        
        if (!$saveUser) return false;        

        # 修改qt_db_data表为删除
        $where = ['database_id' => $database_id];
        if ($delUserIds) $where['user_id'] = ['IN',$delUserIds];
        $saveDbData = model('DbData')->deleteDbData($where);
        if ($saveDbData === false) return false;

        if (!$delUserIds) $delUserIds = $allUserIds;
        # 修改itemRelationData表为删除
        $saveItemRelation = model('DbItemRelationData')->deleteItemRelationData(['user_id' => ['IN',$delUserIds]]);
        if ($saveItemRelation === false) return false;

        # 写入日志

        return true;
    }
    /**
     * 删除用户
     * @param int  $database_id 数据库id
     * @param int  $delUserIds 删除的用户id
     * @author MSQ 2021-8-7
    **/
    public function deleteUser($where = [])
    {
        if (!$where) return true;
        $where['status'] = 1;
        return $this->update(['status' => 0,'relation_status' => 0],$where);
    }
    /**
     * 修改病例时同步用户信息
     * @param int  $database_id 数据库id
     * @param int  $delUserIds 删除的用户id
     * @author MSQ 2021-8-7
    **/
    public function updataInfoBySaveDatabaseData($user_id = 0,$saveUserInfo = [])
    {
        if (!$user_id) return false;
        if (!$saveUserInfo) return true;

        $basicItemKey = model('DbItem')->getBasicItemKey();
        $basicLen = strlen($basicItemKey)+2;

        $saveData = [];
        # 基本信息相关字段组装
        foreach ($saveUserInfo as $key => $value) {
            $userKey = substr($key,$basicLen);
            $saveData[$userKey] = $value;
            if ($userKey == 'user_sex') {
                # 性别 查找选择的选项代表的性别
                $option_key = model('DbQuestionOption')->getDetails($value,'option_key');
                $saveData[$userKey] = 0;//保密
                if ($option_key == 'man') {
                    $saveData[$userKey] = 1;// 男
                } elseif ($option_key == 'woman') {
                    $saveData[$userKey] = 2; // 女
                } 
            }
        }
        $res = $this->update($saveData,['id' => $user_id]);
        if (!$res) return false;
        return true;
    }
    # --------------------------------- 数据处理类接口 END ----------------------------------

    
}
